<template>
  <div class="login-container">
    <div class="login-box">
      <div class="login-header">
        <img src="/favicon.ico" alt="logo" class="login-logo" />
        <h2>智芯ERP管理系统</h2>
      </div>
      
      <el-form :model="form" :rules="rules" ref="loginForm" class="login-form">
        <el-form-item prop="username">
          <el-input 
            v-model="form.username" 
            placeholder="请输入用户名"
            prefix-icon="User"
            size="large"
          />
        </el-form-item>
        
        <el-form-item prop="password">
          <el-input 
            v-model="form.password" 
            type="password" 
            placeholder="请输入密码"
            prefix-icon="Lock"
            size="large"
            @keyup.enter="onLogin"
          />
        </el-form-item>
        
        <el-form-item>
          <el-button 
            type="primary" 
            size="large" 
            style="width: 100%"
            :loading="loading"
            @click="onLogin"
          >
            登录
          </el-button>
        </el-form-item>
      </el-form>
      
      <div class="login-tips">
        <p>测试账号：admin / 123456</p>
        <p>其他角色：manager, sales, purchaser, warehouse, finance, hr, user</p>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useUserStore } from '@/store/user'
import { useRouter } from 'vue-router'
import axios from 'axios'
import { ElMessage } from 'element-plus'

const form = ref({ username: '', password: '' })
const loading = ref(false)
const loginForm = ref(null)
const userStore = useUserStore()
const router = useRouter()

const rules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' }
  ]
}

const onLogin = async () => {
  if (!loginForm.value) return
  
  try {
    await loginForm.value.validate()
    loading.value = true
    
    // 调用登录接口
    const res = await axios.post('http://localhost:8081/api/user/login', form.value)
    
    if (res.data.code === 200) {
      // 保存用户信息和token
      userStore.setUserInfo(res.data.data.user)
      userStore.setToken(res.data.data.token)
      
      // 获取用户权限
      try {
        const permRes = await axios.get(`http://localhost:8081/api/user/${res.data.data.user.id}/permissions`, {
          headers: { Authorization: `Bearer ${res.data.data.token}` }
        })
        
        if (permRes.data.code === 200) {
          userStore.setPermissions(permRes.data.data)
          ElMessage.success('登录成功')
          router.push('/')
        } else {
          ElMessage.error('获取权限失败：' + permRes.data.msg)
        }
      } catch (error) {
        console.error('获取权限失败:', error)
        ElMessage.error('获取权限失败，请重试')
      }
    } else {
      ElMessage.error(res.data.msg || '登录失败')
    }
  } catch (error) {
    console.error('登录失败:', error)
    if (error.response) {
      ElMessage.error('登录失败：' + (error.response.data?.msg || '网络错误'))
    } else {
      ElMessage.error('登录失败，请检查网络连接')
    }
  } finally {
    loading.value = false
  }
}

onMounted(() => {
  // 如果已经登录，直接跳转到首页
  if (userStore.token) {
    router.push('/')
  }
})
</script>

<style scoped>
.login-container {
  height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  display: flex;
  justify-content: center;
  align-items: center;
}

.login-box {
  width: 400px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
  padding: 40px;
}

.login-header {
  text-align: center;
  margin-bottom: 30px;
}

.login-logo {
  width: 64px;
  height: 64px;
  margin-bottom: 16px;
}

.login-header h2 {
  margin: 0;
  color: #303133;
  font-size: 24px;
  font-weight: 500;
}

.login-form {
  margin-bottom: 20px;
}

.login-tips {
  text-align: center;
  color: #909399;
  font-size: 14px;
}

.login-tips p {
  margin: 5px 0;
}
</style> 